// 商品API服务
const API_BASE_URL = 'http://localhost:8080/api/products'

import { getToken } from './authService'

// 获取认证token
const getAuthToken = (): string | null => {
  return getToken()
}

// 创建带认证头的请求配置
const createAuthHeaders = (): HeadersInit => {
  const token = getAuthToken()
  const headers: HeadersInit = {
    'Content-Type': 'application/json'
  }
  
  if (token) {
    headers['Authorization'] = `Bearer ${token}`
  }
  
  return headers
}

export interface ProductRequest {
  name: string
  description?: string
  price: number
  stock: number
  category?: string
  imageUrl?: string
}

export interface ProductResponse {
  id: number
  name: string
  description?: string
  price: number
  stock: number
  category?: string
  imageUrl?: string
  isActive: boolean
  createdAt: string
  updatedAt: string
}

export interface ApiResponse<T> {
  success: boolean
  message: string
  data: T
}

// 添加商品
export const addProduct = async (productData: ProductRequest): Promise<ApiResponse<ProductResponse>> => {
  try {
    const response = await fetch(API_BASE_URL, {
      method: 'POST',
      headers: createAuthHeaders(),
      body: JSON.stringify(productData)
    })
    
    return await response.json()
  } catch (error) {
    console.error('添加商品API调用失败:', error)
    throw new Error('网络错误，请检查后端服务是否启动')
  }
}

// 获取所有商品
export const getAllProducts = async (): Promise<ApiResponse<ProductResponse[]>> => {
  try {
    const response = await fetch(API_BASE_URL, {
      method: 'GET',
      headers: createAuthHeaders()
    })
    return await response.json()
  } catch (error) {
    console.error('获取商品列表API调用失败:', error)
    throw new Error('网络错误，请检查后端服务是否启动')
  }
}

// 根据ID获取商品
export const getProductById = async (id: number): Promise<ApiResponse<ProductResponse>> => {
  try {
    const response = await fetch(`${API_BASE_URL}/${id}`, {
      method: 'GET',
      headers: createAuthHeaders()
    })
    return await response.json()
  } catch (error) {
    console.error('获取商品详情API调用失败:', error)
    throw new Error('网络错误，请检查后端服务是否启动')
  }
}

// 更新商品
export const updateProduct = async (id: number, productData: ProductRequest): Promise<ApiResponse<ProductResponse>> => {
  try {
    const response = await fetch(`${API_BASE_URL}/${id}`, {
      method: 'PUT',
      headers: createAuthHeaders(),
      body: JSON.stringify(productData)
    })
    
    return await response.json()
  } catch (error) {
    console.error('更新商品API调用失败:', error)
    throw new Error('网络错误，请检查后端服务是否启动')
  }
}

// 删除商品
export const deleteProduct = async (id: number): Promise<ApiResponse<void>> => {
  try {
    const response = await fetch(`${API_BASE_URL}/${id}`, {
      method: 'DELETE',
      headers: createAuthHeaders()
    })
    
    return await response.json()
  } catch (error) {
    console.error('删除商品API调用失败:', error)
    throw new Error('网络错误，请检查后端服务是否启动')
  }
}

// 更新商品库存
export const updateProductStock = async (id: number, stock: number): Promise<ApiResponse<ProductResponse>> => {
  try {
    const response = await fetch(`${API_BASE_URL}/${id}/stock?stock=${stock}`, {
      method: 'PATCH',
      headers: createAuthHeaders()
    })
    
    return await response.json()
  } catch (error) {
    console.error('更新库存API调用失败:', error)
    throw new Error('网络错误，请检查后端服务是否启动')
  }
}

// 搜索商品
export const searchProducts = async (name: string): Promise<ApiResponse<ProductResponse[]>> => {
  try {
    const response = await fetch(`${API_BASE_URL}/search?name=${encodeURIComponent(name)}`, {
      method: 'GET',
      headers: createAuthHeaders()
    })
    return await response.json()
  } catch (error) {
    console.error('搜索商品API调用失败:', error)
    throw new Error('网络错误，请检查后端服务是否启动')
  }
}

// 根据分类获取商品
export const getProductsByCategory = async (category: string): Promise<ApiResponse<ProductResponse[]>> => {
  try {
    const response = await fetch(`${API_BASE_URL}/category/${encodeURIComponent(category)}`, {
      method: 'GET',
      headers: createAuthHeaders()
    })
    return await response.json()
  } catch (error) {
    console.error('根据分类获取商品API调用失败:', error)
    throw new Error('网络错误，请检查后端服务是否启动')
  }
}

// 获取库存不足商品
export const getLowStockProducts = async (threshold: number = 10): Promise<ApiResponse<ProductResponse[]>> => {
  try {
    const response = await fetch(`${API_BASE_URL}/low-stock?threshold=${threshold}`, {
      method: 'GET',
      headers: createAuthHeaders()
    })
    return await response.json()
  } catch (error) {
    console.error('获取库存不足商品API调用失败:', error)
    throw new Error('网络错误，请检查后端服务是否启动')
  }
}

// 获取所有分类
export const getAllCategories = async (): Promise<ApiResponse<string[]>> => {
  try {
    const response = await fetch(`${API_BASE_URL}/categories`, {
      method: 'GET',
      headers: createAuthHeaders()
    })
    return await response.json()
  } catch (error) {
    console.error('获取分类API调用失败:', error)
    throw new Error('网络错误，请检查后端服务是否启动')
  }
} 